package it.unibz.ti2.internetPizzeria.servlets;

import it.unibz.ti2.internetPizzeria.dao.OrderDAO;
import it.unibz.ti2.internetPizzeria.entities.Order;
import it.unibz.ti2.internetPizzeria.utils.ServletUtil;
import it.unibz.ti2.internetPizzeria.webAttributes.UserInfo;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Responsible for canceling order of specified id. Order will be cancelled only if its customer is currently logged in.
 */
public class CancelOrder extends HttpServlet {

	private static final long serialVersionUID = 9014591331358611813L;

	protected void doGet(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {
		this.doPost(arg0, arg1);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		OrderDAO orderDAO = null;
		try {
			orderDAO = new OrderDAO();
			
			UserInfo userInfo = (UserInfo)request.getSession().getAttribute("userInfo");
			String orderIdParam = request.getParameter("orderId");
			if (orderIdParam != null && !orderIdParam.isEmpty()){
				orderDAO.openSession();
				long orderId = Long.parseLong(orderIdParam);
				Order order = orderDAO.getOrder(orderId);
				if (order.getCustomer().getId() == userInfo.getId()){
					order.setStatus(Order.StatusCancelled);
					orderDAO.update(order);
				}
			}
			
			ServletUtil.redirect(request, response, "/checkOrderStatus");
			
		} catch (Exception ex) {			
			ex.printStackTrace();
		} finally {
			if (orderDAO != null){
				orderDAO.closeSession();
			}
		}
	}
}
